package com.lzy.mall.auth.controller.v1;

import cn.hutool.core.date.DateUtil;
import com.alibaba.nacos.common.utils.UuidUtils;
import com.lzy.mall.common.constant.AuthServerConstant;
import com.lzy.mall.auth.entity.UmsMember;
import com.lzy.mall.auth.feign.MemberFeignService;
import com.lzy.mall.auth.feign.ThirdPartFeignService;
import com.lzy.mall.auth.vo.TokenDTO;
import com.lzy.mall.auth.vo.UserLoginVo;
import com.lzy.mall.auth.vo.UserRegisterVo;
import com.lzy.mall.common.exception.CommonError;
import com.lzy.mall.common.utils.ResultUtils;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @author lzy
 * @date 2021/9/26 23:28
 */
@RestController
@RequestMapping("v1")
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
@Slf4j
@Api(tags = "登录", value = "登录")
public class MallLoginController {

    private final ThirdPartFeignService thirdPartFeignService;

    private final StringRedisTemplate redisTemplate;

    private final MemberFeignService memberFeignService;

    @ResponseBody
    @GetMapping("/sms/snedcode")
    @ApiOperation(value = "注册短信验证", notes = "注册短信验证")
    public ResultUtils sendCode(@RequestParam("phone") String phone) {
        String code = UuidUtils.generateUuid().substring(0, 6);

        //TODO 手机短信验证
        redisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone,code,10, TimeUnit.MINUTES);

        try {
            thirdPartFeignService.sendCode(phone, code);
        } catch (Exception exception) {
            log.info("远程接口调用异常");
            return ResultUtils.error("短信发送异常");
        }
        return ResultUtils.ok();
    }

    @PostMapping("/register")
    @ApiOperation(value = "注册", notes = "注册")
    public ResultUtils registerV1(UserRegisterVo vo) {

        //TODO 手机短信验证
        try {
            ResultUtils r = memberFeignService.register(vo);
        } catch (Exception exception) {
            log.info("注册失败");
            return ResultUtils.error(CommonError.REGISTERED_ERROR);
        }
        return ResultUtils.ok("注册成功");
    }

    @PostMapping("/login")
    @ApiOperation(value = "登录", notes = "登录")
    public ResultUtils<TokenDTO> login(UserLoginVo vo){
        //远程登录
        try {
            ResultUtils login = memberFeignService.login(vo);
            UmsMember data = (UmsMember) login.getBean("data", UmsMember.class);
            String token = Jwts.builder()
                    .setSubject(data.getId().toString())
                    .setIssuedAt(DateUtil.date())
                    .signWith(SignatureAlgorithm.HS256, AuthServerConstant.secretKey)
                    .setExpiration(new Date(System.currentTimeMillis() + 86400000))
                    .compact();
            TokenDTO tokenDTO = new TokenDTO();
            tokenDTO.setUserInfo(data);
            tokenDTO.setToken(token);
            return ResultUtils.ok(tokenDTO);
        } catch (Exception exception) {
            return ResultUtils.error(CommonError.LOGIN_ERROR);
        }
    }
}
